<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;

class OnlineUserResource extends BaseResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        // 计算在线时长（如果字段不存在，使用login_at计算）
        $onlineDuration = 0;
        try {
            if (isset($this->attributes['online_duration'])) {
                // 字段存在，尝试更新
                if ($this->login_at) {
                    try {
                        $this->updateOnlineDuration();
                    } catch (\Exception $e) {
                        // 更新失败，忽略
                    }
                }
                $onlineDuration = $this->online_duration ?? 0;
            } elseif ($this->login_at) {
                // 字段不存在，使用login_at计算
                $onlineDuration = now()->diffInSeconds($this->login_at);
            }
        } catch (\Exception $e) {
            // 如果计算失败，使用默认值
            $onlineDuration = 0;
        }
        
        return [
            'id' => $this->id,
            'user_id' => $this->user_id,
            'username' => $this->username,
            'token' => $this->token,
            'ip' => $this->ip,
            'user_agent' => $this->user_agent,
            'login_at' => $this->formatDateTime($this->login_at),
            'last_activity_at' => $this->formatDateTime($this->last_activity_at),
            'online_duration' => $onlineDuration,
            'formatted_online_duration' => $this->formatDuration($onlineDuration),
            'user' => $this->whenLoaded('user', function () {
                return [
                    'id' => $this->user->id,
                    'username' => $this->user->username,
                    'nickname' => $this->user->nickname,
                    'email' => $this->user->email,
                    'avatar' => $this->user->avatar,
                ];
            }),
            'created_at' => $this->formatDateTime($this->created_at),
            'updated_at' => $this->formatDateTime($this->updated_at),
        ];
    }
    
    /**
     * 格式化在线时长
     *
     * @param int $seconds
     * @return string
     */
    protected function formatDuration(int $seconds): string
    {
        if ($seconds < 60) {
            return $seconds . '秒';
        } elseif ($seconds < 3600) {
            $minutes = floor($seconds / 60);
            $remainingSeconds = $seconds % 60;
            return $minutes . '分' . ($remainingSeconds > 0 ? $remainingSeconds . '秒' : '');
        } elseif ($seconds < 86400) {
            $hours = floor($seconds / 3600);
            $remainingMinutes = floor(($seconds % 3600) / 60);
            return $hours . '小时' . ($remainingMinutes > 0 ? $remainingMinutes . '分' : '');
        } else {
            $days = floor($seconds / 86400);
            $remainingHours = floor(($seconds % 86400) / 3600);
            return $days . '天' . ($remainingHours > 0 ? $remainingHours . '小时' : '');
        }
    }
}
